<?php
namespace api\modules\v1\controllers;
use api\common\controllers\UserController as U;
use api\modules\v1\models\News;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
use Yii;

class AttentionController extends U
{
    public $modelClass = 'api\modules\v1\models\Attention';

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'],$actions['update'], $actions['create'], $actions['delete'], $actions['view']); //卸载操作
        return $actions;
    }

    /*
     * 添加关注
     * @return array
     * @throws HttpException
     * @throws ServerErrorHttpException
     */
    public function actionCreate(){
        $model = new $this->modelClass();
        $model->aid = Yii::$app->request->post('aid');
        $model->uid = Yii::$app->user->identity->id;
        $model->atime = date('Y-m-d H:i:s');
        if($model->aid == $model->uid){
            throw new HttpException(401,'无法关注自己',0);
        }
        if($model->findOne(['aid'=>$model->aid,'uid'=>$model->uid])){
            throw new HttpException(401,'已关注',0);
        }
        if($model->save()){
            $model->sendAttentionMsg($model->aid);//关注消息发送
            return [
                "message"=>"关注成功!",
            ];
        }elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('由于不明原因未能创建对象.');
        }else{
            throw new HttpException(401,array_values($model->getFirstErrors())[0],0);
        }
    }

    /*
     * 取消关注
     * @return array
     * @throws HttpException
     * @throws ServerErrorHttpException
     */
    public function actionDel(){
        $model = new $this->modelClass();
        $aid = Yii::$app->request->post('aid');//关注的用户
        if(empty($aid)) throw new HttpException(401,'参数aid不能为空',0);
        if($model->deleteAll(['aid'=>$aid,'uid'=>Yii::$app->user->identity->id])){
            return [
                "message"=>"取消关注成功!",
            ];
        }elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('由于不明原因未能创建对象.');
        }else{
            throw new HttpException(401,array_values($model->getFirstErrors())[0],0);
        }
    }

    /*
     * 获取关注列表
     * @param $id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionList(){
        $searchModel = new $this->modelClass();
        $dataProvider = $searchModel->getList();
        return $dataProvider;
    }

}